package com.ncp.servlet.cart;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.util.UtilDate;
import com.ncp.model.biz.cart.HandleOrderBiz;
import com.ncp.model.biz.cart.ShoppingCart;
import com.ncp.model.biz.tools.common.TimeTools;
import com.ncp.model.biz.tools.common.UserTools;
import com.ncp.model.entity.cart.CartBean;
import com.ncp.model.entity.order.OrderBasic;
import com.ncp.model.entity.order.OrderDetail;

public class CommitOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/html");
		String userLoginName = (String)request.getSession().getAttribute("LoginName");
		//System.out.println("LoginName = "+userLoginName);
		if("".equals(userLoginName)||userLoginName==null){
			out.print("<script language=javascript>alert('请登录！');window.location.replace('index.jsp');</script>"); 
		}else if((ShoppingCart)request.getSession().getAttribute("cart")==null){
			out.print("<script language=javascript>alert('购物车内没有任何商品，请重新选择商品！');window.location.replace('index.jsp');</script>");
		}else{
			this.handleOrder(request, response);
		}
	}
	
	public void handleOrder(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//String userID = (String)request.getSession().getAttribute("userid");
		//判断用户是否登录
		String userLoginName = (String)request.getSession().getAttribute("LoginName");
		int userID = Integer.parseInt(new UserTools().getUserIdByLoginName(userLoginName));
	
		
		//从session中取出购物车内的数据
		ShoppingCart cart = (ShoppingCart)request.getSession().getAttribute("cart");
		
		//调用工具生成订单号
		String orderID = UtilDate.getOrderNum();
		String paymentType = request.getParameter("pay_method");
		float totalPrice = Float.parseFloat(cart.getTotalprice()+"");
		String orderStatus = "WAIT_BUYER_PAY"; //该状态表示“已产生一笔订单，等待买家付款”。
		
		int receiverID = Integer.parseInt(request.getParameter("addressID"));
		
		String logisticsType = request.getParameter("logistics_type");
		//暂时设置为BUYER_PAY（买家承担运费）
		String logisticsPayment = "BUYER_PAY";
		String tradeID = "";
		String buyerAccount = "";
		String expressID = "";
		//判断收货人信息
		
		System.out.println("orderID = "+orderID);
		System.out.println("paymentType = "+paymentType);
		System.out.println("totalPrice = "+totalPrice);
		System.out.println("orderStatus = "+orderStatus);
		
		System.out.println("logisticsType = "+logisticsType);
		System.out.println("logisticsPayment = "+logisticsPayment);
		System.out.println("expressID = "+expressID);
		
		OrderBasic orderBasic = new OrderBasic();
		orderBasic.setOrderID(orderID);
		orderBasic.setUserID(userID);
		orderBasic.setOrderTime(TimeTools.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
		orderBasic.setPaymentType(paymentType);
		orderBasic.setTotalPrice(totalPrice);
		orderBasic.setOrderStatus(orderStatus);
		
		orderBasic.setLogisticsType(logisticsType);
		orderBasic.setLogisticsPayment(logisticsPayment);
		orderBasic.setTradeID(tradeID);
		orderBasic.setBuyerAccount(buyerAccount);
		//orderBasic.setConsignmentTime("0000-00-00 00:00:00");
		orderBasic.setConsignmentTime(null);
		orderBasic.setExpressID(expressID);
		orderBasic.setReceiverID(receiverID);
		
		HandleOrderBiz handleOrderBiz = new HandleOrderBiz();
		List<OrderDetail> list1 = new ArrayList<OrderDetail>();
		
		Map<String,CartBean> cartMap = null;
		cartMap = cart.getCartMap();
		CartBean cartBean = null;
		Iterator<String> hmkey = cartMap.keySet().iterator();
		while(hmkey.hasNext()){
			cartBean = cartMap.get(hmkey.next());
			OrderDetail orderDetail = new OrderDetail();
			orderDetail.setProductID(Integer.parseInt(cartBean.getProductID()));
			orderDetail.setProductPrice(Float.parseFloat(cartBean.getRetailPrice()+""));
			orderDetail.setProductNumber(cartBean.getProductNumOfCart());
			
			//保存 订单详细信息
			int result = handleOrderBiz.saveOrderDetail(orderID, orderDetail);
			if(result != 0){
				list1.add(orderDetail);
				
				//更新ProductBaisc表中的产品数量
				int result1 = handleOrderBiz.reduceProductNumber(Integer.parseInt(cartBean.getProductID()), cartBean.getProductNumOfCart());
				if(result1 == 1){
					System.out.println("更新ProductBaisc表中的产品数量成功！");
				}else{
					System.out.println("更新ProductBaisc表中的产品数量出错！");
				}
			}else{
				System.out.println("OrderDetail表插入数据出错！");
			}
		}
		//保存订单基本信息
		int result1 = handleOrderBiz.saveOrderBasic(orderBasic);
		if(result1 != 0 ){
			request.setAttribute("list1", list1);
			request.setAttribute("orderBasic", orderBasic);
			request.setAttribute("ordermessage", "订单提交成功！");
			//清除session中的数据
			cart.clearCart();
			request.getRequestDispatcher("pages/cart/confirmpayment.jsp").forward(request, response);
		}
		
		
}

}
